package com.study.gamecube.controller;

import com.study.gamecube.pojo.GameGoods;
import com.study.gamecube.service.GameGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.ValidationException;
import java.util.List;

/**
 * shop服务向外暴露的goods_api
 * 使用人员：员工[对游戏商品CURD]
 *
 * @author peng
 */
@RestController
@RequestMapping("/gameGoods")
public class GameGoodsController {
    @Autowired
    private GameGoodsService gameGoodsService;

    /**
     * 上架游戏货品
     *
     * @param gameGoods
     * @return
     */
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @CacheEvict(value = "shopGoodsCache",allEntries = true)
    public GameGoods addGoods(@Valid @RequestBody GameGoods gameGoods, BindingResult result) {
        if(result.hasErrors()) {
            throw new ValidationException(result.toString());
        }
        return gameGoodsService.addGoods(gameGoods);
    }

    /**
     * 下架游戏货品
     *
     * @param id
     */
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.ACCEPTED)
    @CacheEvict(value = "shopGoodsCache",allEntries = true)
    public void deleteGoods(@PathVariable("id") Long id) {
        gameGoodsService.deleteById(id);
    }

    /**
     * 修改游戏货品
     *
     * @param gameGoods
     * @return
     */
    @PutMapping
    @ResponseStatus(HttpStatus.OK)
    @CacheEvict(value = "shopGoodsCache",allEntries = true)
    public GameGoods updateGoods(@RequestBody GameGoods gameGoods) {
        return gameGoodsService.updateGoods(gameGoods);
    }

    /**
     * 查询所有游戏货品
     *
     * @return
     */
    @Cacheable(value = "shopGoodsCache")
    @GetMapping
    public List<GameGoods> findAll() {
        return gameGoodsService.findAll();
    }
}
